home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / urllib2.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  44KB  |  1,328 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''An extensible library for opening URLs using a variety of protocols
  5.  
  6. The simplest way to use this module is to call the urlopen function,
  7. which accepts a string containing a URL or a Request object (described
  8. below).  It opens the URL and returns the results as file-like
  9. object; the returned object has some extra methods described below.
  10.  
  11. The OpenerDirector manages a collection of Handler objects that do
  12. all the actual work.  Each Handler implements a particular protocol or
  13. option.  The OpenerDirector is a composite object that invokes the
  14. Handlers needed to open the requested URL.  For example, the
  15. HTTPHandler performs HTTP GET and POST requests and deals with
  16. non-error returns.  The HTTPRedirectHandler automatically deals with
  17. HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
  18. deals with digest authentication.
  19.  
  20. urlopen(url, data=None) -- Basic usage is the same as original
  21. urllib.  pass the url and optionally data to post to an HTTP URL, and
  22. get a file-like object back.  One difference is that you can also pass
  23. a Request instance instead of URL.  Raises a URLError (subclass of
  24. IOError); for HTTP errors, raises an HTTPError, which can also be
  25. treated as a valid response.
  26.  
  27. build_opener -- Function that creates a new OpenerDirector instance.
  28. Will install the default handlers.  Accepts one or more Handlers as
  29. arguments, either instances or Handler classes that it will
  30. instantiate.  If one of the argument is a subclass of the default
  31. handler, the argument will be installed instead of the default.
  32.  
  33. install_opener -- Installs a new opener as the default opener.
  34.  
  35. objects of interest:
  36. OpenerDirector --
  37.  
  38. Request -- An object that encapsulates the state of a request.  The
  39. state can be as simple as the URL.  It can also include extra HTTP
  40. headers, e.g. a User-Agent.
  41.  
  42. BaseHandler --
  43.  
  44. exceptions:
  45. URLError -- A subclass of IOError, individual protocols have their own
  46. specific subclass.
  47.  
  48. HTTPError -- Also a valid HTTP response, so you can treat an HTTP error
  49. as an exceptional event or valid response.
  50.  
  51. internals:
  52. BaseHandler and parent
  53. _call_chain conventions
  54.  
  55. Example usage:
  56.  
  57. import urllib2
  58.  
  59. # set up authentication info
  60. authinfo = urllib2.HTTPBasicAuthHandler()
  61. authinfo.add_password(realm=\'PDQ Application\',
  62.                       uri=\'https://mahler:8092/site-updates.py\',
  63.                       user=\'klem\',
  64.                       passwd=\'geheim$parole\')
  65.  
  66. proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
  67.  
  68. # build a new opener that adds authentication and caching FTP handlers
  69. opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler)
  70.  
  71. # install it
  72. urllib2.install_opener(opener)
  73.  
  74. f = urllib2.urlopen(\'http://www.python.org/\')
  75.  
  76.  
  77. '''
  78. import base64
  79. import hashlib
  80. import httplib
  81. import mimetools
  82. import os
  83. import posixpath
  84. import random
  85. import re
  86. import socket
  87. import sys
  88. import time
  89. import urlparse
  90. import bisect
  91.  
  92. try:
  93.     from cStringIO import StringIO
  94. except ImportError:
  95.     from StringIO import StringIO
  96.  
  97. from urllib import unwrap, unquote, splittype, splithost, quote, addinfourl, splitport, splitattr, ftpwrapper, splituser, splitpasswd, splitvalue
  98. from urllib import localhost, url2pathname, getproxies, proxy_bypass
  99. __version__ = sys.version[:3]
  100. _opener = None
  101.  
  102. def urlopen(url, data = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  103.     global _opener
  104.     if _opener is None:
  105.         _opener = build_opener()
  106.     
  107.     return _opener.open(url, data, timeout)
  108.  
  109.  
  110. def install_opener(opener):
  111.     global _opener
  112.     _opener = opener
  113.  
  114.  
  115. class URLError(IOError):
  116.     
  117.     def __init__(self, reason):
  118.         self.args = (reason,)
  119.         self.reason = reason
  120.  
  121.     
  122.     def __str__(self):
  123.         return '<urlopen error %s>' % self.reason
  124.  
  125.  
  126.  
  127. class HTTPError(URLError, addinfourl):
  128.     '''Raised when HTTP error occurs, but also acts like non-error return'''
  129.     __super_init = addinfourl.__init__
  130.     
  131.     def __init__(self, url, code, msg, hdrs, fp):
  132.         self.code = code
  133.         self.msg = msg
  134.         self.hdrs = hdrs
  135.         self.fp = fp
  136.         self.filename = url
  137.         if fp is not None:
  138.             self._HTTPError__super_init(fp, hdrs, url, code)
  139.         
  140.  
  141.     
  142.     def __str__(self):
  143.         return 'HTTP Error %s: %s' % (self.code, self.msg)
  144.  
  145.  
  146. _cut_port_re = re.compile(':\\d+$')
  147.  
  148. def request_host(request):
  149.     '''Return request-host, as defined by RFC 2965.
  150.  
  151.     Variation from RFC: returned value is lowercased, for convenient
  152.     comparison.
  153.  
  154.     '''
  155.     url = request.get_full_url()
  156.     host = urlparse.urlparse(url)[1]
  157.     if host == '':
  158.         host = request.get_header('Host', '')
  159.     
  160.     host = _cut_port_re.sub('', host, 1)
  161.     return host.lower()
  162.  
  163.  
  164. class Request:
  165.     
  166.     def __init__(self, url, data = None, headers = { }, origin_req_host = None, unverifiable = False):
  167.         self._Request__original = unwrap(url)
  168.         self.type = None
  169.         self.host = None
  170.         self.port = None
  171.         self._tunnel_host = None
  172.         self.data = data
  173.         self.headers = { }
  174.         for key, value in headers.items():
  175.             self.add_header(key, value)
  176.         
  177.         self.unredirected_hdrs = { }
  178.         if origin_req_host is None:
  179.             origin_req_host = request_host(self)
  180.         
  181.         self.origin_req_host = origin_req_host
  182.         self.unverifiable = unverifiable
  183.  
  184.     
  185.     def __getattr__(self, attr):
  186.         if attr[:12] == '_Request__r_':
  187.             name = attr[12:]
  188.             if hasattr(Request, 'get_' + name):
  189.                 getattr(self, 'get_' + name)()
  190.                 return getattr(self, attr)
  191.         
  192.         raise AttributeError, attr
  193.  
  194.     
  195.     def get_method(self):
  196.         if self.has_data():
  197.             return 'POST'
  198.         return 'GET'
  199.  
  200.     
  201.     def add_data(self, data):
  202.         self.data = data
  203.  
  204.     
  205.     def has_data(self):
  206.         return self.data is not None
  207.  
  208.     
  209.     def get_data(self):
  210.         return self.data
  211.  
  212.     
  213.     def get_full_url(self):
  214.         return self._Request__original
  215.  
  216.     
  217.     def get_type(self):
  218.         if self.type is None:
  219.             (self.type, self._Request__r_type) = splittype(self._Request__original)
  220.             if self.type is None:
  221.                 raise ValueError, 'unknown url type: %s' % self._Request__original
  222.             self.type is None
  223.         
  224.         return self.type
  225.  
  226.     
  227.     def get_host(self):
  228.         if self.host is None:
  229.             (self.host, self._Request__r_host) = splithost(self._Request__r_type)
  230.             if self.host:
  231.                 self.host = unquote(self.host)
  232.             
  233.         
  234.         return self.host
  235.  
  236.     
  237.     def get_selector(self):
  238.         return self._Request__r_host
  239.  
  240.     
  241.     def set_proxy(self, host, type):
  242.         if self.type == 'https' and not (self._tunnel_host):
  243.             self._tunnel_host = self.host
  244.         else:
  245.             self.type = type
  246.             self._Request__r_host = self._Request__original
  247.         self.host = host
  248.  
  249.     
  250.     def has_proxy(self):
  251.         return self._Request__r_host == self._Request__original
  252.  
  253.     
  254.     def get_origin_req_host(self):
  255.         return self.origin_req_host
  256.  
  257.     
  258.     def is_unverifiable(self):
  259.         return self.unverifiable
  260.  
  261.     
  262.     def add_header(self, key, val):
  263.         self.headers[key.capitalize()] = val
  264.  
  265.     
  266.     def add_unredirected_header(self, key, val):
  267.         self.unredirected_hdrs[key.capitalize()] = val
  268.  
  269.     
  270.     def has_header(self, header_name):
  271.         if not header_name in self.headers:
  272.             pass
  273.         return header_name in self.unredirected_hdrs
  274.  
  275.     
  276.     def get_header(self, header_name, default = None):
  277.         return self.headers.get(header_name, self.unredirected_hdrs.get(header_name, default))
  278.  
  279.     
  280.     def header_items(self):
  281.         hdrs = self.unredirected_hdrs.copy()
  282.         hdrs.update(self.headers)
  283.         return hdrs.items()
  284.  
  285.  
  286.  
  287. class OpenerDirector:
  288.     
  289.     def __init__(self):
  290.         client_version = 'Python-urllib/%s' % __version__
  291.         self.addheaders = [
  292.             ('User-agent', client_version)]
  293.         self.handlers = []
  294.         self.handle_open = { }
  295.         self.handle_error = { }
  296.         self.process_response = { }
  297.         self.process_request = { }
  298.  
  299.     
  300.     def add_handler(self, handler):
  301.         if not hasattr(handler, 'add_parent'):
  302.             raise TypeError('expected BaseHandler instance, got %r' % type(handler))
  303.         hasattr(handler, 'add_parent')
  304.         added = False
  305.         for meth in dir(handler):
  306.             if meth in ('redirect_request', 'do_open', 'proxy_open'):
  307.                 continue
  308.             
  309.             i = meth.find('_')
  310.             protocol = meth[:i]
  311.             condition = meth[i + 1:]
  312.             if condition.startswith('error'):
  313.                 j = condition.find('_') + i + 1
  314.                 kind = meth[j + 1:]
  315.                 
  316.                 try:
  317.                     kind = int(kind)
  318.                 except ValueError:
  319.                     pass
  320.  
  321.                 lookup = self.handle_error.get(protocol, { })
  322.                 self.handle_error[protocol] = lookup
  323.             elif condition == 'open':
  324.                 kind = protocol
  325.                 lookup = self.handle_open
  326.             elif condition == 'response':
  327.                 kind = protocol
  328.                 lookup = self.process_response
  329.             elif condition == 'request':
  330.                 kind = protocol
  331.                 lookup = self.process_request
  332.             
  333.             handlers = lookup.setdefault(kind, [])
  334.             if handlers:
  335.                 bisect.insort(handlers, handler)
  336.             else:
  337.                 handlers.append(handler)
  338.             added = True
  339.         
  340.         if added:
  341.             bisect.insort(self.handlers, handler)
  342.             handler.add_parent(self)
  343.         
  344.  
  345.     
  346.     def close(self):
  347.         pass
  348.  
  349.     
  350.     def _call_chain(self, chain, kind, meth_name, *args):
  351.         handlers = chain.get(kind, ())
  352.         for handler in handlers:
  353.             func = getattr(handler, meth_name)
  354.             result = func(*args)
  355.             if result is not None:
  356.                 return result
  357.         
  358.  
  359.     
  360.     def open(self, fullurl, data = None, timeout = socket._GLOBAL_DEFAULT_TIMEOUT):
  361.         if isinstance(fullurl, basestring):
  362.             req = Request(fullurl, data)
  363.         else:
  364.             req = fullurl
  365.             if data is not None:
  366.                 req.add_data(data)
  367.             
  368.         req.timeout = timeout
  369.         protocol = req.get_type()
  370.         meth_name = protocol + '_request'
  371.         for processor in self.process_request.get(protocol, []):
  372.             meth = getattr(processor, meth_name)
  373.             req = meth(req)
  374.         
  375.         response = self._open(req, data)
  376.         meth_name = protocol + '_response'
  377.         for processor in self.process_response.get(protocol, []):
  378.             meth = getattr(processor, meth_name)
  379.             response = meth(req, response)
  380.         
  381.         return response
  382.  
  383.     
  384.     def _open(self, req, data = None):
  385.         result = self._call_chain(self.handle_open, 'default', 'default_open', req)
  386.         if result:
  387.             return result
  388.         protocol = req.get_type()
  389.         result = self._call_chain(self.handle_open, protocol, protocol + '_open', req)
  390.         if result:
  391.             return result
  392.         return self._call_chain(self.handle_open, 'unknown', 'unknown_open', req)
  393.  
  394.     
  395.     def error(self, proto, *args):
  396.         if proto in ('http', 'https'):
  397.             dict = self.handle_error['http']
  398.             proto = args[2]
  399.             meth_name = 'http_error_%s' % proto
  400.             http_err = 1
  401.             orig_args = args
  402.         else:
  403.             dict = self.handle_error
  404.             meth_name = proto + '_error'
  405.             http_err = 0
  406.         args = (dict, proto, meth_name) + args
  407.         result = self._call_chain(*args)
  408.         if result:
  409.             return result
  410.         if http_err:
  411.             args = (dict, 'default', 'http_error_default') + orig_args
  412.             return self._call_chain(*args)
  413.  
  414.  
  415.  
  416. def build_opener(*handlers):
  417.     '''Create an opener object from a list of handlers.
  418.  
  419.     The opener will use several default handlers, including support
  420.     for HTTP and FTP.
  421.  
  422.     If any of the handlers passed as arguments are subclasses of the
  423.     default handlers, the default handlers will not be used.
  424.     '''
  425.     import types
  426.     
  427.     def isclass(obj):
  428.         if not isinstance(obj, types.ClassType):
  429.             pass
  430.         return hasattr(obj, '__bases__')
  431.  
  432.     opener = OpenerDirector()
  433.     default_classes = [
  434.         ProxyHandler,
  435.         UnknownHandler,
  436.         HTTPHandler,
  437.         HTTPDefaultErrorHandler,
  438.         HTTPRedirectHandler,
  439.         FTPHandler,
  440.         FileHandler,
  441.         HTTPErrorProcessor]
  442.     if hasattr(httplib, 'HTTPS'):
  443.         default_classes.append(HTTPSHandler)
  444.     
  445.     skip = set()
  446.     for klass in default_classes:
  447.         for check in handlers:
  448.             if isclass(check):
  449.                 if issubclass(check, klass):
  450.                     skip.add(klass)
  451.                 
  452.             issubclass(check, klass)
  453.             if isinstance(check, klass):
  454.                 skip.add(klass)
  455.                 continue
  456.         
  457.     
  458.     for klass in skip:
  459.         default_classes.remove(klass)
  460.     
  461.     for klass in default_classes:
  462.         opener.add_handler(klass())
  463.     
  464.     for h in handlers:
  465.         if isclass(h):
  466.             h = h()
  467.         
  468.         opener.add_handler(h)
  469.     
  470.     return opener
  471.  
  472.  
  473. class BaseHandler:
  474.     handler_order = 500
  475.     
  476.     def add_parent(self, parent):
  477.         self.parent = parent
  478.  
  479.     
  480.     def close(self):
  481.         pass
  482.  
  483.     
  484.     def __lt__(self, other):
  485.         if not hasattr(other, 'handler_order'):
  486.             return True
  487.         return self.handler_order < other.handler_order
  488.  
  489.  
  490.  
  491. class HTTPErrorProcessor(BaseHandler):
  492.     '''Process HTTP error responses.'''
  493.     handler_order = 1000
  494.     
  495.     def http_response(self, request, response):
  496.         code = response.code
  497.         msg = response.msg
  498.         hdrs = response.info()
  499.         if code <= code:
  500.             pass
  501.         elif not code < 300:
  502.             response = self.parent.error('http', request, response, code, msg, hdrs)
  503.         
  504.         return response
  505.  
  506.     https_response = http_response
  507.  
  508.  
  509. class HTTPDefaultErrorHandler(BaseHandler):
  510.     
  511.     def http_error_default(self, req, fp, code, msg, hdrs):
  512.         raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  513.  
  514.  
  515.  
  516. class HTTPRedirectHandler(BaseHandler):
  517.     max_repeats = 4
  518.     max_redirections = 10
  519.     
  520.     def redirect_request(self, req, fp, code, msg, headers, newurl):
  521.         """Return a Request or None in response to a redirect.
  522.  
  523.         This is called by the http_error_30x methods when a
  524.         redirection response is received.  If a redirection should
  525.         take place, return a new Request to allow http_error_30x to
  526.         perform the redirect.  Otherwise, raise HTTPError if no-one
  527.         else should try to handle this url.  Return None if you can't
  528.         but another Handler might.
  529.         """
  530.         m = req.get_method()
  531.         if (code in (301, 302, 303, 307) or m in ('GET', 'HEAD') or code in (301, 302, 303)) and m == 'POST':
  532.             newurl = newurl.replace(' ', '%20')
  533.             newheaders = dict((lambda .0: for k, v in .0:
  534. if k.lower() not in ('content-length', 'content-type'):
  535. (k, v)continue)(req.headers.items()))
  536.             return Request(newurl, headers = newheaders, origin_req_host = req.get_origin_req_host(), unverifiable = True)
  537.         raise HTTPError(req.get_full_url(), code, msg, headers, fp)
  538.  
  539.     
  540.     def http_error_302(self, req, fp, code, msg, headers):
  541.         if 'location' in headers:
  542.             newurl = headers.getheaders('location')[0]
  543.         elif 'uri' in headers:
  544.             newurl = headers.getheaders('uri')[0]
  545.         else:
  546.             return None
  547.         urlparts = ('location' in headers).urlparse(newurl)
  548.         if not urlparts.path:
  549.             urlparts = list(urlparts)
  550.             urlparts[2] = '/'
  551.         
  552.         newurl = urlparse.urlunparse(urlparts)
  553.         newurl = urlparse.urljoin(req.get_full_url(), newurl)
  554.         new = self.redirect_request(req, fp, code, msg, headers, newurl)
  555.         if new is None:
  556.             return None
  557.         visited[newurl] = visited.get(newurl, 0) + 1
  558.         fp.read()
  559.         fp.close()
  560.         return self.parent.open(new, timeout = req.timeout)
  561.  
  562.     http_error_301 = http_error_303 = http_error_307 = http_error_302
  563.     inf_msg = 'The HTTP server returned a redirect error that would lead to an infinite loop.\nThe last 30x error message was:\n'
  564.  
  565.  
  566. def _parse_proxy(proxy):
  567.     """Return (scheme, user, password, host/port) given a URL or an authority.
  568.  
  569.     If a URL is supplied, it must have an authority (host:port) component.
  570.     According to RFC 3986, having an authority component means the URL must
  571.     have two slashes after the scheme:
  572.  
  573.     >>> _parse_proxy('file:/ftp.example.com/')
  574.     Traceback (most recent call last):
  575.     ValueError: proxy URL with no authority: 'file:/ftp.example.com/'
  576.  
  577.     The first three items of the returned tuple may be None.
  578.  
  579.     Examples of authority parsing:
  580.  
  581.     >>> _parse_proxy('proxy.example.com')
  582.     (None, None, None, 'proxy.example.com')
  583.     >>> _parse_proxy('proxy.example.com:3128')
  584.     (None, None, None, 'proxy.example.com:3128')
  585.  
  586.     The authority component may optionally include userinfo (assumed to be
  587.     username:password):
  588.  
  589.     >>> _parse_proxy('joe:password@proxy.example.com')
  590.     (None, 'joe', 'password', 'proxy.example.com')
  591.     >>> _parse_proxy('joe:password@proxy.example.com:3128')
  592.     (None, 'joe', 'password', 'proxy.example.com:3128')
  593.  
  594.     Same examples, but with URLs instead:
  595.  
  596.     >>> _parse_proxy('http://proxy.example.com/')
  597.     ('http', None, None, 'proxy.example.com')
  598.     >>> _parse_proxy('http://proxy.example.com:3128/')
  599.     ('http', None, None, 'proxy.example.com:3128')
  600.     >>> _parse_proxy('http://joe:password@proxy.example.com/')
  601.     ('http', 'joe', 'password', 'proxy.example.com')
  602.     >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
  603.     ('http', 'joe', 'password', 'proxy.example.com:3128')
  604.  
  605.     Everything after the authority is ignored:
  606.  
  607.     >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
  608.     ('ftp', 'joe', 'password', 'proxy.example.com')
  609.  
  610.     Test for no trailing '/' case:
  611.  
  612.     >>> _parse_proxy('http://joe:password@proxy.example.com')
  613.     ('http', 'joe', 'password', 'proxy.example.com')
  614.  
  615.     """
  616.     (scheme, r_scheme) = splittype(proxy)
  617.     if not r_scheme.startswith('/'):
  618.         scheme = None
  619.         authority = proxy
  620.     elif not r_scheme.startswith('//'):
  621.         raise ValueError('proxy URL with no authority: %r' % proxy)
  622.     
  623.     end = r_scheme.find('/', 2)
  624.     if end == -1:
  625.         end = None
  626.     
  627.     authority = r_scheme[2:end]
  628.     (userinfo, hostport) = splituser(authority)
  629.     if userinfo is not None:
  630.         (user, password) = splitpasswd(userinfo)
  631.     else:
  632.         user = None
  633.         password = None
  634.     return (scheme, user, password, hostport)
  635.  
  636.  
  637. class ProxyHandler(BaseHandler):
  638.     handler_order = 100
  639.     
  640.     def __init__(self, proxies = None):
  641.         if proxies is None:
  642.             proxies = getproxies()
  643.         
  644.         if not hasattr(proxies, 'has_key'):
  645.             raise AssertionError, 'proxies must be a mapping'
  646.         self.proxies = proxies
  647.         for type, url in proxies.items():
  648.             setattr(self, '%s_open' % type, (lambda r, proxy = url, type = type, meth = self.proxy_open: meth(r, proxy, type)))
  649.         
  650.  
  651.     
  652.     def proxy_open(self, req, proxy, type):
  653.         orig_type = req.get_type()
  654.         (proxy_type, user, password, hostport) = _parse_proxy(proxy)
  655.         if proxy_type is None:
  656.             proxy_type = orig_type
  657.         
  658.         if req.host and proxy_bypass(req.host):
  659.             return None
  660.         if user and password:
  661.             user_pass = '%s:%s' % (unquote(user), unquote(password))
  662.             creds = base64.b64encode(user_pass).strip()
  663.             req.add_header('Proxy-authorization', 'Basic ' + creds)
  664.         
  665.         hostport = unquote(hostport)
  666.         req.set_proxy(hostport, proxy_type)
  667.         if orig_type == proxy_type or orig_type == 'https':
  668.             return None
  669.         return self.parent.open(req, timeout = req.timeout)
  670.  
  671.  
  672.  
  673. class HTTPPasswordMgr:
  674.     
  675.     def __init__(self):
  676.         self.passwd = { }
  677.  
  678.     
  679.     def add_password(self, realm, uri, user, passwd):
  680.         if isinstance(uri, basestring):
  681.             uri = [
  682.                 uri]
  683.         
  684.         if realm not in self.passwd:
  685.             self.passwd[realm] = { }
  686.         
  687.         for default_port in (True, False):
  688.             reduced_uri = []([ self.reduce_uri(u, default_port) for u in uri ])
  689.             self.passwd[realm][reduced_uri] = (user, passwd)
  690.         
  691.  
  692.     
  693.     def find_user_password(self, realm, authuri):
  694.         domains = self.passwd.get(realm, { })
  695.         for default_port in (True, False):
  696.             reduced_authuri = self.reduce_uri(authuri, default_port)
  697.             for uris, authinfo in domains.iteritems():
  698.                 for uri in uris:
  699.                     if self.is_suburi(uri, reduced_authuri):
  700.                         return authinfo
  701.                 
  702.             
  703.         
  704.         return (None, None)
  705.  
  706.     
  707.     def reduce_uri(self, uri, default_port = True):
  708.         '''Accept authority or URI and extract only the authority and path.'''
  709.         parts = urlparse.urlsplit(uri)
  710.         if parts[1]:
  711.             scheme = parts[0]
  712.             authority = parts[1]
  713.             if not parts[2]:
  714.                 pass
  715.             path = '/'
  716.         else:
  717.             scheme = None
  718.             authority = uri
  719.             path = '/'
  720.         (host, port) = splitport(authority)
  721.         if default_port and port is None and scheme is not None:
  722.             dport = {
  723.                 'http': 80,
  724.                 'https': 443 }.get(scheme)
  725.             if dport is not None:
  726.                 authority = '%s:%d' % (host, dport)
  727.             
  728.         
  729.         return (authority, path)
  730.  
  731.     
  732.     def is_suburi(self, base, test):
  733.         '''Check if test is below base in a URI tree
  734.  
  735.         Both args must be URIs in reduced form.
  736.         '''
  737.         if base == test:
  738.             return True
  739.         if base[0] != test[0]:
  740.             return False
  741.         common = posixpath.commonprefix((base[1], test[1]))
  742.         if len(common) == len(base[1]):
  743.             return True
  744.         return False
  745.  
  746.  
  747.  
  748. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  749.     
  750.     def find_user_password(self, realm, authuri):
  751.         (user, password) = HTTPPasswordMgr.find_user_password(self, realm, authuri)
  752.         if user is not None:
  753.             return (user, password)
  754.         return HTTPPasswordMgr.find_user_password(self, None, authuri)
  755.  
  756.  
  757.  
  758. class AbstractBasicAuthHandler:
  759.     rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+realm=(["\'])(.*?)\\2', re.I)
  760.     
  761.     def __init__(self, password_mgr = None):
  762.         if password_mgr is None:
  763.             password_mgr = HTTPPasswordMgr()
  764.         
  765.         self.passwd = password_mgr
  766.         self.add_password = self.passwd.add_password
  767.  
  768.     
  769.     def http_error_auth_reqed(self, authreq, host, req, headers):
  770.         authreq = headers.get(authreq, None)
  771.         if authreq:
  772.             mo = AbstractBasicAuthHandler.rx.search(authreq)
  773.             if mo:
  774.                 (scheme, quote, realm) = mo.groups()
  775.                 if scheme.lower() == 'basic':
  776.                     return self.retry_http_basic_auth(host, req, realm)
  777.             
  778.         
  779.  
  780.     
  781.     def retry_http_basic_auth(self, host, req, realm):
  782.         (user, pw) = self.passwd.find_user_password(realm, host)
  783.         if pw is not None:
  784.             raw = '%s:%s' % (user, pw)
  785.             auth = 'Basic %s' % base64.b64encode(raw).strip()
  786.             if req.headers.get(self.auth_header, None) == auth:
  787.                 return None
  788.             req.add_header(self.auth_header, auth)
  789.             return self.parent.open(req, timeout = req.timeout)
  790.         return None
  791.  
  792.  
  793.  
  794. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  795.     auth_header = 'Authorization'
  796.     
  797.     def http_error_401(self, req, fp, code, msg, headers):
  798.         url = req.get_full_url()
  799.         return self.http_error_auth_reqed('www-authenticate', url, req, headers)
  800.  
  801.  
  802.  
  803. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  804.     auth_header = 'Proxy-authorization'
  805.     
  806.     def http_error_407(self, req, fp, code, msg, headers):
  807.         authority = req.get_host()
  808.         return self.http_error_auth_reqed('proxy-authenticate', authority, req, headers)
  809.  
  810.  
  811.  
  812. def randombytes(n):
  813.     '''Return n random bytes.'''
  814.     if os.path.exists('/dev/urandom'):
  815.         f = open('/dev/urandom')
  816.         s = f.read(n)
  817.         f.close()
  818.         return s
  819.     L = [ chr(random.randrange(0, 256)) for i in range(n) ]
  820.     return ''.join(L)
  821.  
  822.  
  823. class AbstractDigestAuthHandler:
  824.     
  825.     def __init__(self, passwd = None):
  826.         if passwd is None:
  827.             passwd = HTTPPasswordMgr()
  828.         
  829.         self.passwd = passwd
  830.         self.add_password = self.passwd.add_password
  831.         self.retried = 0
  832.         self.nonce_count = 0
  833.  
  834.     
  835.     def reset_retry_count(self):
  836.         self.retried = 0
  837.  
  838.     
  839.     def http_error_auth_reqed(self, auth_header, host, req, headers):
  840.         authreq = headers.get(auth_header, None)
  841.         if self.retried > 5:
  842.             raise HTTPError(req.get_full_url(), 401, 'digest auth failed', headers, None)
  843.         self.retried > 5
  844.         self.retried += 1
  845.  
  846.     
  847.     def retry_http_digest_auth(self, req, auth):
  848.         (token, challenge) = auth.split(' ', 1)
  849.         chal = parse_keqv_list(parse_http_list(challenge))
  850.         auth = self.get_authorization(req, chal)
  851.         if auth:
  852.             auth_val = 'Digest %s' % auth
  853.             if req.headers.get(self.auth_header, None) == auth_val:
  854.                 return None
  855.             req.add_unredirected_header(self.auth_header, auth_val)
  856.             resp = self.parent.open(req, timeout = req.timeout)
  857.             return resp
  858.  
  859.     
  860.     def get_cnonce(self, nonce):
  861.         dig = hashlib.sha1('%s:%s:%s:%s' % (self.nonce_count, nonce, time.ctime(), randombytes(8))).hexdigest()
  862.         return dig[:16]
  863.  
  864.     
  865.     def get_authorization(self, req, chal):
  866.         
  867.         try:
  868.             realm = chal['realm']
  869.             nonce = chal['nonce']
  870.             qop = chal.get('qop')
  871.             algorithm = chal.get('algorithm', 'MD5')
  872.             opaque = chal.get('opaque', None)
  873.         except KeyError:
  874.             return None
  875.  
  876.         (H, KD) = self.get_algorithm_impls(algorithm)
  877.         if H is None:
  878.             return None
  879.         (user, pw) = self.passwd.find_user_password(realm, req.get_full_url())
  880.         if user is None:
  881.             return None
  882.         A1 = '%s:%s:%s' % (user, realm, pw)
  883.         A2 = '%s:%s' % (req.get_method(), req.get_selector())
  884.         if qop == 'auth':
  885.             self.nonce_count += 1
  886.             ncvalue = '%08x' % self.nonce_count
  887.             cnonce = self.get_cnonce(nonce)
  888.             noncebit = '%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, qop, H(A2))
  889.             respdig = KD(H(A1), noncebit)
  890.         elif qop is None:
  891.             respdig = KD(H(A1), '%s:%s' % (nonce, H(A2)))
  892.         else:
  893.             raise URLError("qop '%s' is not supported." % qop)
  894.         base = None if req.has_data() else H is None % (user, realm, nonce, req.get_selector(), respdig)
  895.         if opaque:
  896.             base += ', opaque="%s"' % opaque
  897.         
  898.         if entdig:
  899.             base += ', digest="%s"' % entdig
  900.         
  901.         base += ', algorithm="%s"' % algorithm
  902.         if qop:
  903.             base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  904.         
  905.         return base
  906.  
  907.     
  908.     def get_algorithm_impls(self, algorithm):
  909.         algorithm = algorithm.upper()
  910.         if algorithm == 'MD5':
  911.             
  912.             H = lambda x: hashlib.md5(x).hexdigest()
  913.         elif algorithm == 'SHA':
  914.             
  915.             H = lambda x: hashlib.sha1(x).hexdigest()
  916.         
  917.         
  918.         KD = lambda s, d: H('%s:%s' % (s, d))
  919.         return (H, KD)
  920.  
  921.     
  922.     def get_entity_digest(self, data, chal):
  923.         pass
  924.  
  925.  
  926.  
  927. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  928.     '''An authentication protocol defined by RFC 2069
  929.  
  930.     Digest authentication improves on basic authentication because it
  931.     does not transmit passwords in the clear.
  932.     '''
  933.     auth_header = 'Authorization'
  934.     handler_order = 490
  935.     
  936.     def http_error_401(self, req, fp, code, msg, headers):
  937.         host = urlparse.urlparse(req.get_full_url())[1]
  938.         retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  939.         self.reset_retry_count()
  940.         return retry
  941.  
  942.  
  943.  
  944. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  945.     auth_header = 'Proxy-Authorization'
  946.     handler_order = 490
  947.     
  948.     def http_error_407(self, req, fp, code, msg, headers):
  949.         host = req.get_host()
  950.         retry = self.http_error_auth_reqed('proxy-authenticate', host, req, headers)
  951.         self.reset_retry_count()
  952.         return retry
  953.  
  954.  
  955.  
  956. class AbstractHTTPHandler(BaseHandler):
  957.     
  958.     def __init__(self, debuglevel = 0):
  959.         self._debuglevel = debuglevel
  960.  
  961.     
  962.     def set_http_debuglevel(self, level):
  963.         self._debuglevel = level
  964.  
  965.     
  966.     def do_request_(self, request):
  967.         host = request.get_host()
  968.         if not host:
  969.             raise URLError('no host given')
  970.         host
  971.         if request.has_data():
  972.             data = request.get_data()
  973.             if not request.has_header('Content-type'):
  974.                 request.add_unredirected_header('Content-type', 'application/x-www-form-urlencoded')
  975.             
  976.             if not request.has_header('Content-length'):
  977.                 request.add_unredirected_header('Content-length', '%d' % len(data))
  978.             
  979.         
  980.         sel_host = host
  981.         if request.has_proxy():
  982.             (scheme, sel) = splittype(request.get_selector())
  983.             (sel_host, sel_path) = splithost(sel)
  984.         
  985.         if not request.has_header('Host'):
  986.             request.add_unredirected_header('Host', sel_host)
  987.         
  988.         for name, value in self.parent.addheaders:
  989.             name = name.capitalize()
  990.             if not request.has_header(name):
  991.                 request.add_unredirected_header(name, value)
  992.                 continue
  993.         
  994.         return request
  995.  
  996.     
  997.     def do_open(self, http_class, req):
  998.         '''Return an addinfourl object for the request, using http_class.
  999.  
  1000.         http_class must implement the HTTPConnection API from httplib.
  1001.         The addinfourl return value is a file-like object.  It also
  1002.         has methods and attributes including:
  1003.             - info(): return a mimetools.Message object for the headers
  1004.             - geturl(): return the original request URL
  1005.             - code: HTTP status code
  1006.         '''
  1007.         host = req.get_host()
  1008.         if not host:
  1009.             raise URLError('no host given')
  1010.         host
  1011.         h = http_class(host, timeout = req.timeout)
  1012.         h.set_debuglevel(self._debuglevel)
  1013.         headers = dict(req.headers)
  1014.         headers.update(req.unredirected_hdrs)
  1015.         headers['Connection'] = 'close'
  1016.         headers = dict((lambda .0: for name, val in .0:
  1017. (name.title(), val))(headers.items()))
  1018.         if req._tunnel_host:
  1019.             h._set_tunnel(req._tunnel_host)
  1020.         
  1021.         
  1022.         try:
  1023.             h.request(req.get_method(), req.get_selector(), req.data, headers)
  1024.             r = h.getresponse()
  1025.         except socket.error:
  1026.             err = None
  1027.             raise URLError(err)
  1028.  
  1029.         r.recv = r.read
  1030.         fp = socket._fileobject(r, close = True)
  1031.         resp = addinfourl(fp, r.msg, req.get_full_url())
  1032.         resp.code = r.status
  1033.         resp.msg = r.reason
  1034.         return resp
  1035.  
  1036.  
  1037.  
  1038. class HTTPHandler(AbstractHTTPHandler):
  1039.     
  1040.     def http_open(self, req):
  1041.         return self.do_open(httplib.HTTPConnection, req)
  1042.  
  1043.     http_request = AbstractHTTPHandler.do_request_
  1044.  
  1045. if hasattr(httplib, 'HTTPS'):
  1046.     
  1047.     class HTTPSHandler(AbstractHTTPHandler):
  1048.         
  1049.         def https_open(self, req):
  1050.             return self.do_open(httplib.HTTPSConnection, req)
  1051.  
  1052.         https_request = AbstractHTTPHandler.do_request_
  1053.  
  1054.  
  1055.  
  1056. class HTTPCookieProcessor(BaseHandler):
  1057.     
  1058.     def __init__(self, cookiejar = None):
  1059.         import cookielib as cookielib
  1060.         if cookiejar is None:
  1061.             cookiejar = cookielib.CookieJar()
  1062.         
  1063.         self.cookiejar = cookiejar
  1064.  
  1065.     
  1066.     def http_request(self, request):
  1067.         self.cookiejar.add_cookie_header(request)
  1068.         return request
  1069.  
  1070.     
  1071.     def http_response(self, request, response):
  1072.         self.cookiejar.extract_cookies(response, request)
  1073.         return response
  1074.  
  1075.     https_request = http_request
  1076.     https_response = http_response
  1077.  
  1078.  
  1079. class UnknownHandler(BaseHandler):
  1080.     
  1081.     def unknown_open(self, req):
  1082.         type = req.get_type()
  1083.         raise URLError('unknown url type: %s' % type)
  1084.  
  1085.  
  1086.  
  1087. def parse_keqv_list(l):
  1088.     '''Parse list of key=value strings where keys are not duplicated.'''
  1089.     parsed = { }
  1090.     for elt in l:
  1091.         (k, v) = elt.split('=', 1)
  1092.         if v[0] == '"' and v[-1] == '"':
  1093.             v = v[1:-1]
  1094.         
  1095.         parsed[k] = v
  1096.     
  1097.     return parsed
  1098.  
  1099.  
  1100. def parse_http_list(s):
  1101.     '''Parse lists as described by RFC 2068 Section 2.
  1102.  
  1103.     In particular, parse comma-separated lists where the elements of
  1104.     the list may include quoted-strings.  A quoted-string could
  1105.     contain a comma.  A non-quoted string could have quotes in the
  1106.     middle.  Neither commas nor quotes count if they are escaped.
  1107.     Only double-quotes count, not single-quotes.
  1108.     '''
  1109.     res = []
  1110.     part = ''
  1111.     escape = quote = False
  1112.     for cur in s:
  1113.         if escape:
  1114.             part += cur
  1115.             escape = False
  1116.             continue
  1117.         
  1118.         if quote:
  1119.             if cur == '\\':
  1120.                 escape = True
  1121.                 continue
  1122.             elif cur == '"':
  1123.                 quote = False
  1124.             
  1125.             part += cur
  1126.             continue
  1127.         
  1128.         if cur == ',':
  1129.             res.append(part)
  1130.             part = ''
  1131.             continue
  1132.         
  1133.         if cur == '"':
  1134.             quote = True
  1135.         
  1136.         part += cur
  1137.     
  1138.     if part:
  1139.         res.append(part)
  1140.     
  1141.     return [ part.strip() for part in res ]
  1142.  
  1143.  
  1144. class FileHandler(BaseHandler):
  1145.     
  1146.     def file_open(self, req):
  1147.         url = req.get_selector()
  1148.         if url[:2] == '//' and url[2:3] != '/':
  1149.             req.type = 'ftp'
  1150.             return self.parent.open(req)
  1151.         return self.open_local_file(req)
  1152.  
  1153.     names = None
  1154.     
  1155.     def get_names(self):
  1156.         if FileHandler.names is None:
  1157.             
  1158.             try:
  1159.                 FileHandler.names = (socket.gethostbyname('localhost'), socket.gethostbyname(socket.gethostname()))
  1160.             except socket.gaierror:
  1161.                 FileHandler.names = (socket.gethostbyname('localhost'),)
  1162.             except:
  1163.                 None<EXCEPTION MATCH>socket.gaierror
  1164.             
  1165.  
  1166.         None<EXCEPTION MATCH>socket.gaierror
  1167.         return FileHandler.names
  1168.  
  1169.     
  1170.     def open_local_file(self, req):
  1171.         import email.utils as email
  1172.         import mimetypes as mimetypes
  1173.         host = req.get_host()
  1174.         file = req.get_selector()
  1175.         localfile = url2pathname(file)
  1176.         
  1177.         try:
  1178.             stats = os.stat(localfile)
  1179.             size = stats.st_size
  1180.             modified = email.utils.formatdate(stats.st_mtime, usegmt = True)
  1181.             mtype = mimetypes.guess_type(file)[0]
  1182.             if not mtype:
  1183.                 pass
  1184.             headers = mimetools.Message(StringIO('Content-type: %s\nContent-length: %d\nLast-modified: %s\n' % ('text/plain', size, modified)))
  1185.             if host:
  1186.                 (host, port) = splitport(host)
  1187.             
  1188.             if (not host or not port) and socket.gethostbyname(host) in self.get_names():
  1189.                 return addinfourl(open(localfile, 'rb'), headers, 'file:' + file)
  1190.         except OSError:
  1191.             msg = None
  1192.             raise URLError(msg)
  1193.  
  1194.         raise URLError('file not on local host')
  1195.  
  1196.  
  1197.  
  1198. class FTPHandler(BaseHandler):
  1199.     
  1200.     def ftp_open(self, req):
  1201.         import ftplib as ftplib
  1202.         import mimetypes
  1203.         host = req.get_host()
  1204.         if not host:
  1205.             raise URLError('ftp error: no host given')
  1206.         host
  1207.         (host, port) = splitport(host)
  1208.         if port is None:
  1209.             port = ftplib.FTP_PORT
  1210.         else:
  1211.             port = int(port)
  1212.         (user, host) = splituser(host)
  1213.         if user:
  1214.             (user, passwd) = splitpasswd(user)
  1215.         else:
  1216.             passwd = None
  1217.         host = unquote(host)
  1218.         if not user:
  1219.             pass
  1220.         user = unquote('')
  1221.         if not passwd:
  1222.             pass
  1223.         passwd = unquote('')
  1224.         
  1225.         try:
  1226.             host = socket.gethostbyname(host)
  1227.         except socket.error:
  1228.             msg = None
  1229.             raise URLError(msg)
  1230.  
  1231.         (path, attrs) = splitattr(req.get_selector())
  1232.         dirs = path.split('/')
  1233.         dirs = map(unquote, dirs)
  1234.         dirs = dirs[:-1]
  1235.         file = dirs[-1]
  1236.         if dirs and not dirs[0]:
  1237.             dirs = dirs[1:]
  1238.         
  1239.         
  1240.         try:
  1241.             fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
  1242.             if not file or 'I':
  1243.                 pass
  1244.             type = 'D'
  1245.             for attr in attrs:
  1246.                 (attr, value) = splitvalue(attr)
  1247.                 if attr.lower() == 'type' and value in ('a', 'A', 'i', 'I', 'd', 'D'):
  1248.                     type = value.upper()
  1249.                     continue
  1250.             
  1251.             (fp, retrlen) = fw.retrfile(file, type)
  1252.             headers = ''
  1253.             mtype = mimetypes.guess_type(req.get_full_url())[0]
  1254.             if mtype:
  1255.                 headers += 'Content-type: %s\n' % mtype
  1256.             
  1257.             if retrlen is not None and retrlen >= 0:
  1258.                 headers += 'Content-length: %d\n' % retrlen
  1259.             
  1260.             sf = StringIO(headers)
  1261.             headers = mimetools.Message(sf)
  1262.             return addinfourl(fp, headers, req.get_full_url())
  1263.         except ftplib.all_errors:
  1264.             msg = None
  1265.             raise URLError, 'ftp error: %s' % msg, sys.exc_info()[2]
  1266.  
  1267.  
  1268.     
  1269.     def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1270.         fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
  1271.         return fw
  1272.  
  1273.  
  1274.  
  1275. class CacheFTPHandler(FTPHandler):
  1276.     
  1277.     def __init__(self):
  1278.         self.cache = { }
  1279.         self.timeout = { }
  1280.         self.soonest = 0
  1281.         self.delay = 60
  1282.         self.max_conns = 16
  1283.  
  1284.     
  1285.     def setTimeout(self, t):
  1286.         self.delay = t
  1287.  
  1288.     
  1289.     def setMaxConns(self, m):
  1290.         self.max_conns = m
  1291.  
  1292.     
  1293.     def connect_ftp(self, user, passwd, host, port, dirs, timeout):
  1294.         key = (user, host, port, '/'.join(dirs), timeout)
  1295.         if key in self.cache:
  1296.             self.timeout[key] = time.time() + self.delay
  1297.         else:
  1298.             self.cache[key] = ftpwrapper(user, passwd, host, port, dirs, timeout)
  1299.             self.timeout[key] = time.time() + self.delay
  1300.         self.check_cache()
  1301.         return self.cache[key]
  1302.  
  1303.     
  1304.     def check_cache(self):
  1305.         t = time.time()
  1306.         if self.soonest <= t:
  1307.             for k, v in self.timeout.items():
  1308.                 if v < t:
  1309.                     self.cache[k].close()
  1310.                     del self.cache[k]
  1311.                     del self.timeout[k]
  1312.                     continue
  1313.             
  1314.         
  1315.         self.soonest = min(self.timeout.values())
  1316.         if len(self.cache) == self.max_conns:
  1317.             for k, v in self.timeout.items():
  1318.                 if v == self.soonest:
  1319.                     del self.cache[k]
  1320.                     del self.timeout[k]
  1321.                     break
  1322.                     continue
  1323.             
  1324.             self.soonest = min(self.timeout.values())
  1325.         
  1326.  
  1327.  
  1328.